package client;

import java.io.Console;
import java.io.File;
import java.util.Scanner;

public class ClientConsole {
	public static final int PORT = 7777;
	public static final String HOST = "localhost";
	public static final String KEYSTORES_FOLDER = "keystore" + File.separator;
	public static final String DOCUMENT_ROOT = "client";
	private Scanner scan;
	private String keystorePath;
	private String truststorePath;
	private Console console;

	public ClientConsole() {
		scan = new Scanner(System.in);
		console = System.console();
	}

	public static void main(String[] args) {
		ClientConsole console = new ClientConsole();
		console.findStores();
		console.recieveUserCommands();
	}

	private void findStores() {
		System.out.println("specify your keystore:");
		System.out.print(KEYSTORES_FOLDER);
		keystorePath = KEYSTORES_FOLDER + scan.nextLine();
		System.out.println("specify your truststore:");
		System.out.print(KEYSTORES_FOLDER);
		truststorePath = KEYSTORES_FOLDER + scan.nextLine();
	}

	private void recieveUserCommands() {
		String inputLine = "";
		ClientTransceiver transceiver;

		while (true) {
			System.out.print("request: ");
			inputLine = scan.nextLine();

			if (inputLine.startsWith("get ")) {
				transceiver = connect();
				if (transceiver == null)
					continue;

				transceiver.commandThenListen("get ", getArgument(inputLine));
			} else if (inputLine.startsWith("store ")) {
				transceiver = connect();
				if (transceiver == null)
					continue;
				transceiver.writeFileToServer("store ", getArgument(inputLine));
			} else if (inputLine.startsWith("delete ")) {
				transceiver = connect();
				if (transceiver == null)
					continue;
				transceiver.commandThenListen("delete ", getArgument(inputLine));
			} else if (inputLine.startsWith("create ")) {
				transceiver = connect();
				if (transceiver == null)
					continue;
				transceiver.writeFileToServer("create ", getArgument(inputLine));
			} else if (inputLine.startsWith("list ")) {
				transceiver = connect();
				if (transceiver == null)
					continue;
				transceiver.commandThenListen("list ", getArgument(inputLine));
			} else if (inputLine.startsWith("quit")) {
				break;
			} else {
				System.out.println("unrecognized command");
			}
		}
	}

	private String getArgument(String line) {
		return line.substring(line.indexOf(' ') + 1);
	}

	private ClientTransceiver connect() {
		String password = "";
		System.out.print("password: ");
		try {
			char[] passwordChars = console.readPassword();
	        password = new String(passwordChars);
		} catch (NullPointerException e) {
			password = scan.nextLine();
		}
		ClientAuthenticator connection = new ClientAuthenticator(password,
				keystorePath, truststorePath, HOST, PORT);

		if (connection.connectionFailed())
			return null;

		return new ClientTransceiver(connection, "client");
	}
}
